<template>
  <el-card>
    <!-- 添加按钮 -->
    <el-button type="primary" size="default" icon="Plus" @click="addTradeMark">
      添加品牌
    </el-button>
    <!-- 表头 -->
    <el-table style="margin: 10px 0px" border :data="trademarkArr">
      <el-table-column label="序号" width="80px" align="center" type="index" />
      <el-table-column prop="tmName" label="品牌名称" width="180" />
      <el-table-column label="品牌LOGO">
        <template #="{ row, $index }">
          <img
            :src="row.logoUrl"
            alt="图片丢失了~"
            style="width: 100px; height: 100px"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateTradeMark(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`确定删除${row.tmName}`"
            width="250px"
            icon="delete"
            @confirm="deleteTradeMark(row.id)"
          >
            <template #reference>
              <el-button type="danger" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 50]"
      :background="true"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="totalNumber"
      @size-change="sizeChange"
      @current-change="getHasTradeMark"
    />
  </el-card>

</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import {
  reqTrademark,
  reqDeleteTrademark,
  reqAddOrUpdateTrademark,
} from '@/api/product/trademark'
import type {
  TradeMark,
  TradeMarkResponseData,
  Records,
} from '@/api/product/trademark/type'
import { UploadProps } from 'element-plus/es/components/upload/src/upload'
import { ElMessage } from 'element-plus'

//当前页码
let pageNo = ref<number>(1)
//
let pageSize = ref<number>(3)

let totalNumber = ref<number>(0)
let trademarkArr = ref<Records>([])

// 是否展示弹窗
let dialogFormVisible = ref<boolean>(false)

// 表单新增参数
let trademarkParams = ref<TradeMark>({
  tmName: '',
  logoUrl: '',
})

const getHasTradeMark = async (currenPageNo = 1) => {
  pageNo.value = currenPageNo
  let res: any = await reqTrademark(pageNo.value, pageSize.value)

  if (res.code == 200) {
    totalNumber.value = res.data.total
    trademarkArr.value = res.data.records
  }
}

onMounted(() => {
  getHasTradeMark()
})

const sizeChange = () => {
  getHasTradeMark()
}

let formRef = ref()

const validatorTmName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('品牌名称位数大于等于两位'))
  }
}

const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  if (value) {
    callBack()
  } else {
    callBack(new Error('Logo的图片务必上传'))
  }
}

// 参数校验
const rules = {
  tmName: [
    {
      required: true,
      trigger: 'blur',
      validator: validatorTmName,
    },
  ],
  logoUrl: [
    {
      required: true,
      trigger: 'change',
      validator: validatorLogoUrl,
    },
  ],
}

// 新增
const addTradeMark =async () => {
  dialogFormVisible.value = true
  trademarkParams.value.id = 0
  trademarkParams.value.tmName = ''
  trademarkParams.value.logoUrl = ''

  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}

const handleLogoImageSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  trademarkParams.value.logoUrl = response.data
  formRef.value.clearValidate('logoUrl')
}

const beforeLogoImageUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type === 'image/png' ||
    rawFile.type === 'image/jpeg' ||
    rawFile.type === 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传的文件大小应小于4M',
      })
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传的文件类型必须是PNG|JPG|GIF',
    })
    return false
  }
}

// 更新
const updateTradeMark = (row: TradeMark) => {
  // 清除字段校验
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
  dialogFormVisible.value = true

  // 当前列内容, 赋值到正在编辑的表单字段
  Object.assign(trademarkParams, row)
}

// 删除
const deleteTradeMark = async (id: number) => {
  let res = await reqDeleteTrademark(id)
  console.log(res)

  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })

    //删除后获取最新的数据
    getHasTradeMark(
      trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败',
    })
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/* 上传外边框 */
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.el-icon.logo-image-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
